package com.hd.trans.utils;

import static android.content.Context.TELEPHONY_SERVICE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;

import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.ui.base.AppContextProvider;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class AndroidUtil {
    public static final String recoverDir = "/.hudundevice/";
    private static String[] arrayPower = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    /**
     * 获取手机设备号，Android Q之后会没权限获取到，此方法为未升级系统的活跃用户做备份处理操作
     *
     * @param context context最好使用全局上下文Application
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getDeviceID(Context context) {
        String IMEI = null;
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            IMEI = tm.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return IMEI == null ? "" : IMEI;
    }

    /**
     * 获取AndoridID
     *
     * @param context context最好使用全局上下文Application
     * @return
     */
    @SuppressLint("HardwareIds")
    private static String getAndroidId(Context context) {
        String ANDROID_ID = TranslationInterior.getAndroidId();
        if(TextUtils.isEmpty(ANDROID_ID)){
            ANDROID_ID = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
            TranslationInterior.getTranslationProperty().setAndroidId(ANDROID_ID);
        }
        return ANDROID_ID == null ? "" : ANDROID_ID;
    }

    public static String fillMD5(String md5) {
        return md5.length() == 32 ? md5 : fillMD5("0" + md5);
    }

    /**
     * 获取32位字符串
     */
    public static String getAndroidIdHuDun(Context context) {
        return fillMD5(getAndroidId(context));
    }

    public static boolean autoPower(Context context) {
        //检查是否已经给了权限
        boolean pwerPass = true;
        for (int i = 0; i < arrayPower.length; i++) {
            int checkpermission = ContextCompat.checkSelfPermission(context, arrayPower[i]);
            if (checkpermission != PackageManager.PERMISSION_GRANTED) {
                pwerPass = false;
            }
        }
        return pwerPass;
    }

    /**
     * 检测Sdcard是否存在
     *
     * @return boolean  Sdcard是否存在
     */
    private static boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    public static String getSDCard() {
        String path = "";
        if (isExitsSdcard()) {
            path = Environment.getExternalStorageDirectory().toString();
        }
        return path;
    }

    /**
     * 保存txt文档
     */
    public static void saveText(String text, String path) {
        try {
            FileOutputStream fileInputStream = new FileOutputStream(path);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileInputStream, "UTF-8");
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(text);
            bufferedWriter.flush();
//            outputStreamWriter.write(text)
            outputStreamWriter.flush();
            fileInputStream.flush();
            bufferedWriter.close();
            outputStreamWriter.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 读取txt文件
     */
    public static String readFileOnLine(String filePath) {//输入文件路径
        String fileContent = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                fileContent += line;
            }
            bufferedReader.close();
            inputStreamReader.close();
            fileInputStream.close();
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return fileContent;
    }

    /**
     * 保存Android Q之前的设备号
     *
     * @param deviceID
     * @param context
     */
    public static void saveDeviceID(String deviceID, Context context) {
        if (autoPower(context)) {
            String outPath = getSDCard().concat(recoverDir).concat(context.getResources().getString(R.string.sdk_name).concat(".txt"));
            File file = new File(outPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            saveText(deviceID, outPath);
        }
    }

    /**
     * 读取保存过的Android Q之前的设备号
     *
     * @param context
     * @return
     */
    public static String getSaveDeviceID(Context context) {
        String deviceId = "";
        try {
            String outPath = getSDCard().concat(recoverDir).concat(context.getResources().getString(R.string.sdk_name).concat(".txt"));
            deviceId = readFileOnLine(outPath);
        } catch (Exception e) {
        }
        return deviceId;
    }

    /**
     * 判断是否当前系统为Android Q及以上版本
     *
     * @return
     */
    public static boolean isAndroidQ_Over() {
        boolean flag;
        if (29 <= Build.VERSION.SDK_INT) {
            flag = true;
        } else {
            flag = false;
        }
        return flag;
    }


  /*  public static List<Map<String, Object>> createUserInfo() {
        String avatar = "";
//        String nickName = "";
//        if (!TextUtils.isEmpty(PROFILE.getUserName())){
//            nickName=PROFILE.getUserName();
//        }else {
//            if (!TextUtils.isEmpty(PROFILE.getLoginMobileNumber())){
//                nickName=PROFILE.getLoginMobileNumber();
//            }
//        }

        if (!TextUtils.isEmpty(PreferenceMgr.getInstance().getUserPreference().getUserAvatar())) {
            avatar = PreferenceMgr.getInstance().getUserPreference().getUserAvatar();
        }

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new LinkedHashMap<>();
//        map.put("key","real_name");
//        map.put("value", nickName);
//        list.add(map);

        map = new LinkedHashMap<>();
        map.put("key", "mobile_phone");
        map.put("hidden", true);
        list.add(map);

        String appName = HuDunApp.getInstance().getResources().getString(R.string.app_name).concat(" ").concat(DeviceUtil.getVersionName(HuDunApp.getInstance()));
        map = new LinkedHashMap<>();
        map.put("key", "email");
        map.put("value", appName);
        list.add(map);

        map = new LinkedHashMap<>();
        map.put("key", "avatar");
        map.put("value", avatar);
        list.add(map);

        return list;
    }
*/

    public static String getSenserChanel() {
        Context mContext = AppContextProvider.getContext();
        ApplicationInfo appInfo = null;
        try {
            appInfo = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
        return appInfo.metaData.getString("SENSORS_CHANNEL");
    }

    private static final int TIME = 500;
    private static long lastClickTime = 0;
    /**
     * 处理快速双击，多击事件，在TIME时间内只执行一次事件
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long currentTime = System.currentTimeMillis();
        long timeInterval = currentTime - lastClickTime;
        if (0 < timeInterval && timeInterval < TIME) {
            return true;
        }
        lastClickTime = currentTime;
        return false;
    }
}
